package LinkedList;

public class _445_AddTwoNumbersII {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode r1 = reverse(l1);
        ListNode r2 = reverse(l2);
        ListNode beginNode = new ListNode(Integer.MIN_VALUE);
        ListNode temp = beginNode;
        int carry = 0;
        while(r1!=null || r2!=null){
            if(r1==null){
                int sum = r2.val+carry;
                carry = 0;
                if(sum>9){
                    sum = sum%10;
                    carry = 1;
                }
                temp.next = new ListNode(sum);
            }else if(r2==null){
                int sum = r1.val+carry;
                carry = 0;
                if(sum>9){
                    sum = sum%10;
                    carry = 1;
                }
                temp.next = new ListNode(sum);
            }else{
                int sum = r1.val+r2.val+carry;
                carry = 0;
                if(sum>9){
                    sum = sum%10;
                    carry = 1;
                }
                temp.next = new ListNode(sum);
            }
            r1 = r1.next;
            r2 = r2.next;
        }
        return beginNode.next;
    }
    public ListNode reverse(ListNode head){
        ListNode prev = null;
        while(head!=null){
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
}
